<template>
  <div>
    <div class="search">
      <input v-model="inputSpell" class="search-input" type="text" placeholder="请输入城市名或拼音" />
    </div>
    <div class="search-content" ref="search" v-show="inputSpell">
      <ul>
        <li
          class="search-item border-bottom"
          v-for="(item,index) of list"
          :key="index"
          @click="handleItemClick(item.name)"
        >{{item.name}}</li>
        <li class="search-item border-bottom" v-if="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
import BScroll from 'better-scroll'
export default {
  name: 'citySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      inputSpell: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleItemClick (cityName) {
      this.$store.commit('changeCity', cityName)
      this.$router.push('/')
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    inputSpell () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.inputSpell) {
        this.list = []
        return this.list
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach(element => {
            if (element.spell.indexOf(this.inputSpell) > -1 || element.name.indexOf(this.inputSpell) > -1) {
              result.push(element)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.search)
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl';

.search {
  background: $bgColor;
  height: 0.72rem;
  padding: 0 0.14rem;

  .search-input {
    text-align: center;
    box-sizing: border-box;
    padding: 0 0.4rem;
    width: 100%;
    margin: 0 auto;
    height: 0.62rem;
    line-height: 0.68rem;
    border-radius: 0.08rem;
    color: #666;
  }
}

.search-content {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0;
  background: #eee;

  .search-item {
    line-height: 0.62rem;
    padding-left: 0.2rem;
    background: #fff;
    color: #666;
  }
}
</style>
